package cn.itcast.web_06.cookie.example;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 显示用户的上次访问时间
 */
public class LastAccessServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LastAccessServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 处理响应中文的乱码
	    response.setContentType("text/html;charset=utf-8");
		// 1、获取所有cookie
	    Cookie[] cookies = request.getCookies();
	    String lastTime = null;
	    // 2、遍历cookie数组
	    for (int i = 0; cookies != null && i < cookies.length; i++) {
	        // 3、获取cookie的名称
	        String name = cookies[i].getName();
	        if ("lastAccess".equals(name)) {
	            // 如果获取的name和"lastAccess"名称相同，就获取cookie时间
	            lastTime = cookies[i].getValue();
	        }
	    }
	    // 4、判断是否首次访问，如果cookie里面有时间，就不是第一次访问，否则就是第一次访问
	    if (lastTime == null) {
	        // 第一次访问
	        /*
	        
	        直接把time传入cookie充当value参数会报错：
	        An invalid character [32] was present in the Cookie value
	        原因是"%tF %<tT"中的空格会Cookie被视为无效字符
	        1.删除非法字符
            设置cookie里面相关的值时别用特殊字符。
            那我就想存怎么办？暂时还没找到有用的办法，网上的方法在我这都没用
            
            */
	        String time = String.format("%tF*%<tT", new Date());
	        Cookie cookie = new Cookie("lastAccess", time);
	        // 回写到浏览器
	        response.addCookie(cookie);
	        response.getWriter().println("你是首次访问本网站！！！");
	    } else {
	        // 说明不是第一次访问，把上次访问时间回写到浏览器
	        response.getWriter().println("欢迎回到本网站，你的上次访问时间为：" + lastTime);
	    }
	    /*
	    String time = String.format("%tF %<tT", new Date());
        Cookie cookie = new Cookie("lastAccess", time);
        cookie.setMaxAge(60*60*24*7);
        */
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
